<?php
/**  
 * @author 辰然 <3469807212@qq.com>  
 * @signature "创意无限"  
 * @copyright Copyright (c) 2024 辰然. All rights reserved. 本软件版权归辰然所有，未经许可，不得用于商业用途。  
 */  
function get_like_count($url) {
    // 设置请求头
    $headers = array(
        'User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/122.0.0.0 Safari/537.36',
        'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8',
        'Accept-Language: zh-CN,zh;q=0.9,en;q=0.8'
    );

    try {
        // 初始化CURL
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
        
        // 执行请求
        $response = curl_exec($ch);
        
        if(curl_errno($ch)) {
            throw new Exception(curl_error($ch));
        }
        
        curl_close($ch);
        
        // 使用正则表达式匹配点赞数
        $pattern = '/<meta name="og:xhs:note_like" content="(\d+)"/';
        if(preg_match($pattern, $response, $matches)) {
            return array(
                'success' => true,
                'like_count' => $matches[1],
                'url' => $url
            );
        }
        
        // 如果没找到，保存响应内容以便调试
        file_put_contents('response.html', $response);
        
        return array(
            'success' => false,
            'error' => '未找到点赞数，响应已保存到response.html',
            'url' => $url
        );
        
    } catch(Exception $e) {
        return array(
            'success' => false,
            'error' => '请求失败: ' . $e->getMessage(),
            'url' => $url
        );
    }
}

// 设置响应头
header('Content-Type: application/json; charset=utf-8');
header('Access-Control-Allow-Origin: *');  // 允许跨域请求
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

// 如果是OPTIONS请求（预检请求），直接返回
if ($_SERVER['REQUEST_METHOD'] === 'OPTIONS') {
    exit(0);
}

// 检查请求方法
if ($_SERVER['REQUEST_METHOD'] !== 'POST') {
    echo json_encode(array(
        'success' => false,
        'error' => '只支持POST请求方法'
    ), JSON_UNESCAPED_UNICODE);
    exit;
}

// 获取POST数据
$post_data = json_decode(file_get_contents('php://input'), true);

if (!isset($post_data['url'])) {
    echo json_encode(array(
        'success' => false,
        'error' => '请提供url参数'
    ), JSON_UNESCAPED_UNICODE);
    exit;
}

// 验证URL格式
if (!filter_var($post_data['url'], FILTER_VALIDATE_URL)) {
    echo json_encode(array(
        'success' => false,
        'error' => 'URL格式不正确'
    ), JSON_UNESCAPED_UNICODE);
    exit;
}

// 处理请求
$result = get_like_count($post_data['url']);
echo json_encode($result, JSON_UNESCAPED_UNICODE | JSON_PRETTY_PRINT);

?> 